<template>
  <a-card>
    <a-row>
      <a-col :span="6">
        <div style="position:relative;top:0;left:20px;">
          <!-- <a-input-search v-model="searchValue" style="margin-bottom: 8px;width: 70%" placeholder="搜索" /> -->
          {{ "组织机构" }}

          <Tooltip title="添加公司" v-if="hasCompanies">
            <PlusOutlined @click="addDepart" style="margin-left: 10px;" />
          </Tooltip>
        </div>

        <div style="height: 650px; overflow-y: scroll;margin: 0px 10px">
          <a-spin tip="加载中..." :spinning="spinning">
            <a-input v-show="isOff" v-model:value="departname" @blur="saveDepartName" autofocus
              @pressEnter="saveDepartName" />
            <Tree class="storage_tree" v-if="treeData" :fieldNames="{
              children: 'children',
              title: 'name',
              key: 'id',
            }" :tree-data="treeData" @select="onSelect" :draggable="true"
              @dragstart="handleDragStart(treeData, $event)">
              <template #title="treeData">
                <div class="tree-data-container">
                  <div class="tree-data-header">
                    <!-- <span>{{ treeData.name }}</span> -->
                    <div v-show="treeData.data.isEditMode">
                      <a-input v-model:value="tempDepartname" @blur="updateDepartname(treeData)"
                        @pressEnter="updateDepartname(treeData)" autofocus />
                    </div>
                    <div v-show="!treeData.data.isEditMode" class="tree-node" @dragover.prevent="handleDragOver($event)"
                      @drop="handleDrop(treeData, $event)">

                      <span>{{ treeData.name }}</span>

                      <a-dropdown class="drop-menu-style">
                        <a class="ant-dropdown-link" @click.prevent>
                          操作 <a-icon>
                            <DownOutlined />
                          </a-icon>
                        </a>
                        <template #overlay>
                          <a-menu>
                            <a-menu-item @click="addChildrnDepart(treeData)">
                              新增部门
                            </a-menu-item>
                            <a-popconfirm title="你确定要删除吗?" ok-text="确定" cancel-text="取消"
                              @confirm="tapdeleteDepart(treeData)">
                              <a-menu-item>
                                删除部门
                              </a-menu-item>
                            </a-popconfirm>
                            <a-menu-item @click="updateDepartnameswitch(treeData)">
                              修改部门
                            </a-menu-item>
                          </a-menu>
                        </template>
                      </a-dropdown>
                    </div>
                  </div>
                  <div class="tree-data-input">
                    <a-input v-show="treeData.data.isOffchildrn" autofocus v-model:value="addDepartname"
                      @blur="saveChildrnDepart(treeData)" @pressEnter="saveChildrnDepart(treeData)" />
                  </div>
                </div>
              </template>
            </Tree>
          </a-spin>
        </div>
      </a-col>
      <a-col :span="18">
        <div class="query">
          <a-button type="primary" @click="addDepartusersedit">添加人员</a-button>
        </div>
        <Table :scroll="{ x: 550, y: 550 }" v-if="ddata" :columns="ucolumns" :data-source="ddata" :loading="loading"
          rowKey="id" size="middle" :bordered="ubordered">
          <!-- <span slot="serial" slot-scope="text, record, index">
            {{ (upagination.current - 1) * upagination.pageSize + parseInt(index) + 1 }}
          </span> -->
          <template #bodyCell="{ column, record }">
            <template v-if="column.key == 'name'">
              <a-tooltip placement="topLeft">
                <template #title>
                  <span>{{ record.name }}</span>
                </template>
                {{ record.name }}
              </a-tooltip>
            </template>
            <template v-else-if="column.key == 'isLeader'">
              <a-tooltip placement="topLeft">
                <template #title>
                  <span>{{ record.isLeader == 1 ? '是' : '否' }}</span>
                </template>
                {{ record.isLeader == 1 ? '是' : '否' }}
              </a-tooltip>
            </template>
            <template v-else-if="column.key == 'action'">

              <a-dropdown class="drop-menu-style">
                <a style="color: #2196f8" @click.prevent>操作 <a-icon>
                    <DownOutlined />
                  </a-icon> </a>
                <template #overlay>
                  <a-menu>
                    <a-popconfirm title="你确定要移除吗?" ok-text="确定" cancel-text="取消" @confirm="batchRemoveuser(record)">
                      <a-menu-item>
                        移除
                      </a-menu-item>
                    </a-popconfirm>
                    <!-- <a-menu-item @click="">
                      修改信息
                    </a-menu-item> -->
                  </a-menu>
                </template>
              </a-dropdown>
            </template>
          </template>

        </Table>
        <a-modal v-model:visible="isEditdepart" width="400px" height="600" :title="'添加人员'" @ok="addDepartusers">
          <a-form>
            <a-form-item label="人员" class="projectItem">
              <a-select v-model:value="departUser" :options="departUserOptions" mode="tags"
                :field-names="{ label: 'value', value: 'key' }" placeholder="请选择"
                style="width: 200px;padding-right: 40px;"></a-select>
            </a-form-item>
            <a-form-item label="部门负责人" class="projectItem">
              <a-select v-model:value="leaders" :options="departUserOption" mode="tags"
                :field-names="{ label: 'value', value: 'key' }" placeholder="请选择"
                style="width: 200px;padding-right: 40px;"></a-select>
            </a-form-item>
          </a-form>
        </a-modal>
      </a-col>
    </a-row>
  </a-card>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { PlusOutlined, DownOutlined } from '@ant-design/icons-vue';
import { queryDepartTree, queryUser, saveDepart, deleteDepart, updateDepart, querychildrn, dragDepart, batchRemove, departmentUsers, queryUsers } from '@/api/base/depart/departListApi';
import { APP_USER } from '@/enums/cacheEnum';
import { Storage } from '@/utils/Storage';
import { Tree, Table, Tooltip, message } from 'ant-design-vue'
// const searchValue = ref(undefined); // 搜索值
const spinning = ref(false); // 树的遮罩
const loading = ref(false); // 遮罩是否显示
const ubordered = ref(true); // 表格边框是否显示
const treeData = ref<any>([]); // 查询树数据
const isOff = ref(false); //是否打开添加框
const departname = ref(''); //添加部门是 双向绑定的部门名称departUser
const departUser = ref([]); //选择完添加人之后，组成的人员数组
const leaders = ref([]); //选择完负责人之后，的数组
const editInput = ref<any>(null); // 创建 ref 引用
const addDepartname = ref(''); //子节点 添加部门 双向绑定部门名称
// const queryParam = reactive<any>({
//   id: null,
//   name: null,
//   pageNumber: undefined,
//   pageSize: 20
// });
const ddata = ref([]); // 表格数据
const historySelect = ref<any>(''); //历史点击
const selectedKeys = ref(''); //双向绑定
const tempDepartname = ref('') // 修改部门名称 
const tempparentId = ref('') //拖动临时 父id
const Id = ref('') //拖动临时 id

const sortids = ref<any>([]);
//const isEditMode = ref(false) //修改名称的开关
const userdata = Storage.Get(APP_USER)
const hasCompanies = ref(false);
const userids = ref<any>([])//用户id 数组
const isEditdepart = ref<any>(false) //添加部门人员弹窗开关
const departUserOptions = ref<any>([]); //不在当前部门的其他人员数组
const departUserOption = ref<any>([]);
const ucolumns = [

  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
    align: 'center',
    width: 150,
    scopedSlots: { customRender: 'nameSlot' }
  },
  {
    title: '是否为负责人',
    dataIndex: 'isLeader',
    key: 'isLeader',
    align: 'center',
    width: 150,
    scopedSlots: { customRender: 'isLeaderSlot' }

  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: 120,
    fixed: 'right',
    align: 'center',
    scopedSlots: { customRender: 'operation' }
  }

];

watch(departUser, () => {

  console.log('dsss', departUser);

  console.log('departUserOptions', departUserOptions.value);

  departUserOption.value = departUserOptions.value.filter(item => departUser.value.includes(item.key))
  console.log('departUserOption.value', departUserOption.value);
  console.log('leader', leaders.value)
})




defineOptions({
  name: 'userEdit',
})

//从部门中批量移除成员
const batchRemoveuser = async (record) => {
  console.log('record', record.userId);
  console.log('historySelect', historySelect.value[0]);
  userids.value = []
  userids.value.push(record.userId)

  console.log('userid', userids.value);

  const data = {
    departId: historySelect.value[0],
    userIds: userids.value
  }
  await batchRemove(data)
    .then(res => {
      if (res.code == 0) {
        message.success("成功移除")
        findDi_rel_dept_correctList();
      }
    })
}

//打开添加人员的弹窗 ，同事获取人员数据
const addDepartusersedit = () => {
  isEditdepart.value = true
  queryDepartUser()
}

//将选定人员添加 到当前部门
const addDepartusers = () => {
  console.log('record',);
  const departId = historySelect.value[0]


  // console.log('departUser',departUser.value)
  // console.log('leaders',leaders.value)

  const userids = Object.values(departUser.value);
  const leaderids = Object.values(leaders.value);


  // console.log('userids',userids)
  // console.log('leaderids',leaderids)

  const param = {
    departId: departId,
    userIds: userids,
    department_leader: leaderids,
    tenantid: userdata.tenantid
  }
  departmentUsers(param)
    .then(res => {
      console.log('res', res);
      if (res.code == 0) {
        message.success("成功添加")
        findDi_rel_dept_correctList()
      }
    })

  departUser.value = []
  leaders.value = []

  queryDepartUser()
  isEditdepart.value = false



}

// 查询不在当前部门的人
const queryDepartUser = async () => {
  console.log('historySelect.value[0]', historySelect.value[0]);
  const param = {
    departId: historySelect.value[0]
  }
  await queryUsers(param)
    .then(res => {
      if (res.code == 0) {
        console.log('res.data', res.data);
        departUserOptions.value = res.data.map(item => {
          return {
            key: item.userid,
            value: item.name
          }
        })
      }
      console.log('departUserOptions', departUserOptions.value);
    })
}


// const getSonValue = (list) => {
//   projectUser.value.wwuserids = list.map(item => item.key);
//   magerOptions.value = list
//    console.log('editParam',list)
// }



// /**
//  * 查询
//  */
// const searchDi_rel_dept_correct = () => {
//   queryParam.pageNumber = 1  
//   findDi_rel_dept_correctList()
// };

// 
// const upagination = ref({
//   // 表格分页参数
//   defaultPageSize: 20,
//   total: 0,
//   current: 1,
//   pageSize: 20,
//   showTotal: total => `共${total}条数据`,
//   showSizeChanger: true,
//   pageSizeOptions: ['10', '20', '50', '100']
// });


// 拖动开始
const handleDragStart = (node, event) => {
  console.log('node', node, event);
  tempparentId.value = event.node.parentId
  //设置拖动的节点id
  Id.value = event.node.id
}


// 拖动过程中的事件处理
const handleDragOver = (event) => {
  event.preventDefault();
  // 获取目标节点（可以根据具体情况获取目标节点的位置信息）
  const targetNode = event.target;
  console.log('targetNode', targetNode);
  // 获取目标节点的位置信息
  const targetRect = targetNode.getBoundingClientRect();
  console.log('targetRect获取目标节点的位置信息', targetRect);
  // 获取鼠标相对于窗口的位置
  const clientY = event.clientY;
  // 计算鼠标位置相对于目标节点顶部的位置
  const mouseYRelativeToTarget = clientY - targetRect.top;
  // 如果 mouseYRelativeToTarget 小于目标节点高度的一半，则表示鼠标在目标节点的上半部分，否则在下半部分
  const isMouseAboveMiddle = mouseYRelativeToTarget < targetRect.height / 2;
  if (isMouseAboveMiddle) {
    console.log('处理拖动到了目标节点的上方');

    // 处理拖动到了目标节点的上方
  } else {
    console.log('处理拖动到了目标节点的下方');
    // 处理拖动到了目标节点的下方
  }

}

// 放置（拖动完成）的事件处理
const handleDrop = async (targetNode, event) => {

  // console.log('拖动到了这id的前面或者后面targetNode.data', targetNode.data.id);

  // console.log('event', event);

  // console.log('拖动到了这个id的里面targetNode.data.parentId', targetNode.data.parentId);

  // console.log('被拖动的idId.value', Id.value);

  // console.log('被拖动的父idtempparentId.value', tempparentId.value);
  const param = {
    parentId: targetNode.data.parentId
  }
  //通过  父id 获取子节点  id 的数组
  await querychildrn(param)
    .then(res => {
      console.log('res', res);
      sortids.value = [];
      res.data.forEach(item => {
        console.log('item', item.departid);
        sortids.value.push(item.departid)
      })
    })
  console.log('sortids', sortids.value);
  // 获取目标节点（可以根据具体情况获取目标节点的位置信息）
  const tarNode = event.target;
  console.log('tarNode', tarNode);
  // 获取目标节点的位置信息
  const targetRect = tarNode.getBoundingClientRect();
  console.log('targetRect获取目标节点的位置信息', targetRect);
  // 获取鼠标相对于窗口的位置
  const clientY = event.clientY;
  // 计算鼠标位置相对于目标节点顶部的位置
  const mouseYRelativeToTarget = clientY - targetRect.top;

  // 如果 mouseYRelativeToTarget 小于目标节点高度的一半，则表示鼠标在目标节点的上半部分，否则在下半部分
  const isMouseAboveMiddle = mouseYRelativeToTarget < targetRect.height / 2;
  if (tempparentId.value == targetNode.data.parentId) {
    //被拖动id下标
    const index = sortids.value.indexOf(Id.value);
    //删除下表未 index  的 属性
    // 如果找到了索引，就删除该元素
    if (index !== -1) {
      sortids.value.splice(index, 1);
    }
  }
  if (isMouseAboveMiddle) {
    console.log('处理拖动到了目标节点的上方');
    const index = sortids.value.indexOf(targetNode.data.id);
    if (index !== -1) {
      sortids.value.splice(index, 0, Id.value); // 在目标节点的前面插入
    }
    // 处理拖动到了目标节点的上方
  } else {
    console.log('处理拖动到了目标节点的下方');
    const index = sortids.value.indexOf(targetNode.data.id);
    if (index !== -1) {
      sortids.value.splice(index + 1, 0, Id.value); // 在目标节点的后面插入
    }
    // 处理拖动到了目标节点的下方
  }
  console.log('数组', sortids.value);
  const body = {
    parentId: targetNode.data.parentId,
    curId: Id.value,
    sortIds: sortids.value
  }
  console.log('body', body);
  //更新树节点数据
  dragDepart(body)
    .then(res => {
      if (res.code == 0) {
        message.success('拖动成功')
        getTree();
      } else {
        message.error('拖动失败')
      }
    })
}
//打开input的方法 更新部门名称开关
const updateDepartnameswitch = (treeu) => {
  //将原本的名称赋值给 临时双向绑定的 名称
  modifyAllIsEditMode(treeData.value)
  modifyAllIsOffchildrn(treeData.value)
  tempDepartname.value = treeu.data.name
  treeu.data.isEditMode = true;
}

const modifyAllIsEditMode = (nodes) => {
  nodes.forEach(node => {
    // 修改当前节点
    node.isEditMode = false; // 假设要修改的属性是 isOffchildrn
    // 递归修改子节点
    if (node.children && node.children.length > 0) {
      modifyAllIsEditMode(node.children);
    }
  });
};



//重命名 部门名称
const updateDepartname = (treeu) => {
  const param = {
    departId: treeu.data.id,
    name: tempDepartname.value,
  }
  updateDepart(param)
    .then(res => {
      if (res.code == 0) {
        message.success('修改成功')
        getTree();
      } else {
        message.error('修改失败')
      }
    })
}
//删除部门
const tapdeleteDepart = (treet) => {
  //onsole.log('treet', treet.data.id);
  const param = {
    departId: treet.data.id
  }
  deleteDepart(param)
    .then(res => {
      if (res.code == 0) {
        message.success('删除成功')
        getTree();
      } else {
        message.error('删除失败')
      }

    })
}

//子节点新增部门
const addChildrnDepart = (trees) => {
  // treeData.value.isOffchildrn.value = true;

  // 调用递归函数，从根节点开始修改所有节点
  modifyAllIsEditMode(treeData.value)
  modifyAllIsOffchildrn(treeData.value)
  console.log('treeData', treeData.value);

  trees.data.isOffchildrn = true;
  console.log('trees', trees);

}

const modifyAllIsOffchildrn = (nodes) => {
  nodes.forEach(node => {
    // 修改当前节点
    node.isOffchildrn = false; // 假设要修改的属性是 isOffchildrn
    // 递归修改子节点
    if (node.children && node.children.length > 0) {
      modifyAllIsOffchildrn (node.children);
    }
  });
};



//保存 子节点 新增部门
const saveChildrnDepart = async (treec) => {
  console.log('treeData', treec);
  if (addDepartname.value === '') {
    message.error('部门名称不能为空')
    treec.data.isOffchildrn = false;
    getTree()
    return
  }
  const a = {
    name: addDepartname.value,
    parentId: treec.data.id,
    tenantId: userdata.tenantid
  }
  await saveDepart(a)
    .then(res => {
      if (res.code == 0) {
        message.success('保存成功')
        getTree();
      } else {
        message.error('保存失败')
      }
    })
  treec.data.isOffchildrn = false;
  addDepartname.value = ''
}
//获取部门树数据
const getTree = async () => {
  //console.log('ss', userdata.tenantid);
  const param = {
    tenantId: userdata.tenantid
  }
  await queryDepartTree(param)
    .then(res => {
      if (res.code == 0) {
        treeData.value = []
        treeData.value = res.data;
        if (treeData.value !== null) {
          hasCompanies.value = false
        } else {
          //没有公司的时候将 显示添加公司的按钮
          hasCompanies.value = true
        }
        //console.log('ssss', res);
        //console.log('zzzz', treeData.value);
      } else {
        console.error("获取数据失败");
      }
    })
  spinning.value = false;
};
// 树选中 
const onSelect = (selectedKey) => {
  console.log('selectdKey', selectedKey);
  if (selectedKey.length == 0) {
    // selectedKeys为双向绑定的变量,return的话就不进行后续操作
    // 友友们可以根据情况进行改造
    selectedKeys.value = historySelect.value
    return
  } else {
    historySelect.value = selectedKey
    selectedKeys.value = selectedKey
  }
  //console.log('ks', selectedKey);
  //console.log('ks,data', ks, data);
  queryDepartUser()
  findDi_rel_dept_correctList()
};

// /**
//  * 查询
//  */
// const searchDi_rel_dept_correct = () => {
//   queryParam.pageNumber = 1  
//   findDi_rel_dept_correctList()
// };

//查询部门列表
const findDi_rel_dept_correctList = async () => {
  ddata.value = []
  loading.value = true
  //console.log('selectedKeys.value', selectedKeys.value[0]);
  await queryUser({ departId: selectedKeys.value[0] })
    .then(res => {
      //console.log('res', res);
      if (res.code == 0) {
        ddata.value = res.data
        // 将当前页码和数量与后台绑定绑定
        // upagination.total.value = res.data.total
        // upagination.current.value = res.data.current
        // upagination.pageSize.value = res.data.size
        // 如果查询时间太短，延迟0.5
        loading.value = false;
      } else {
        message.error("获取数据失败");
        loading.value = false;
      }
    })
};
//添加公司
const addDepart = () => {
  isOff.value = true;
  //console.success("操作成功");
};
//保存公司
const saveDepartName = () => {
  if (departname.value === '') {
    //console.log('departname',departname.value)
    message.error('公司名称不能为空')
    isOff.value = false
    return
  }
  const a = {
    name: departname.value,
    parentId: "0",
    tenantId: userdata.tenantid
  }
  saveDepart(a)
    .then(res => {
      if (res.code == 0) {
        message.success('保存成功')
        getTree();
      } else {
        message.error('保存失败')
      }
    })
  isOff.value = false
  departname.value = ''
};
onMounted(() => {
  getTree();
});


</script>
<style lang="less" scoped>
/* your styles here */
.table-page-search-submitButtons {
  display: block;
  margin-bottom: 24px;
  white-space: nowrap;
}

.table-page-search-submitButtons .btn_primary_color {
  margin-right: 8px;
  /* 调整第一个按钮的右侧间距 */
}

.table-page-search-submitButtons .btn_normal_color {
  margin-left: 8px;
  /* 调整第二个按钮的左侧间距 */
}

.drop-menu-style {
  margin-left: 20px;
  display: inline-block;
  color: #3a3434;
  font-size: 13px;

}

.ant-dropdown-trigger {
  color: #3a3434;
}

.tree-data-container {
  display: flex;
  flex-direction: column;
}

.tree-data-header {
  display: flex;
  align-items: center;
}

.projectItem {
  padding-left: 0px;
  margin-right: 40px;
  padding-right: 20px;

  ::v-deep .ant-col {
    width: auto;
    height: auto;
  }
}

.ant-select-selector {
  margin-right: 20px;
}
</style>
